package com.lag.transfer.factory;

import com.lag.transfer.annotation.MyDefinedTransactional;
import com.lag.transfer.utils.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @author June
 * @since 2020年12月
 */
// @Component("proxyFactory")
public class ProxyFactory {

    //@Autowired
    private TransactionManager transactionManager;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    /**
     * JDK动态代理
     * @param obj 委托对象
     * @return 代理对象
     */
    public Object getJDKProxy(Object obj) {
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
            new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    Object result = null;
                    Method originalMethod = obj.getClass().getDeclaredMethod(method.getName(),method.getParameterTypes());
                    MyDefinedTransactional myTransactional = originalMethod.getAnnotation(MyDefinedTransactional.class);
                    if (myTransactional == null) {
                        return method.invoke(obj, args);
                    }
                    try {
                        transactionManager.beginTransaction();
                        // 调用原有业务逻辑
                        result = method.invoke(obj, args);
                        transactionManager.commit();
                    } catch (Exception e) {
                        e.printStackTrace();
                        transactionManager.rollback();
                        throw e;
                    }
                    return result;
                }
            });
    }

    /**
     * 使用cglib动态代理生成代理对象
     * @param obj 委托对象
     * @return 代理对象
     */
    public Object getCglibProxy(Object obj) {
        return  Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                Object result = null;
                try {
                    transactionManager.beginTransaction();
                    result = method.invoke(obj, args);
                    transactionManager.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                    transactionManager.rollback();
                    throw e;
                }
                return result;
            }
        });
    }
}
